﻿using Common.Core.Cache;
using Common.Core.Extensions;

namespace Common.Core.Encrypt
{
    /// <summary>
    /// RSA公私钥缓存类，目前默认2小时
    /// </summary>
    public class PubPrivateKeys
    {
        /// <summary>
        /// 生成公钥和私钥缓存 返回公钥/私钥
        /// 如果是多节点部署需要依赖redis缓存
        /// </summary>
        /// <param name="isMemoryCache">是否使用MemoryCache</param>
        /// <returns></returns>
        public static RsaKey CreatePublicKeyToCache(bool isMemoryCache = false)
        {
            CacheHelper helper = new CacheHelper(isMemoryCache);

            var rsaKey = RsaCrypt.GenerateRsaKeys(RsaKeyType.PKCS8, 2048);

            //添加缓存,默认2小时
            helper.Add(CacheKeys.ServerPublicKey, rsaKey.ToPkcsPublicKey(), TimeSpan.FromMilliseconds(7200000));
            //缓存公钥私钥 java 公钥 java私钥
            helper.Add(String.Format(CacheKeys.ServerPublicPriKeyMd5, DEncrypt.EncryptMd532(rsaKey.ToPkcsPublicKey())), $"{rsaKey.PublicKey}:{rsaKey.PrivateKey}", TimeSpan.FromMilliseconds(7205000));

            return rsaKey;
        }

        /// <summary>
        /// 获取 RSA公钥
        /// </summary>
        /// <param name="isMemoryCache">是否使用MemoryCache</param>
        /// <returns></returns>
        public static string GetPkcsPublicKeyFromCache(bool isMemoryCache = false)
        {
            //return publickey;
            CacheHelper helper = new CacheHelper(isMemoryCache);
            var pubkey = helper.Get(CacheKeys.ServerPublicKey);
            if (pubkey == null)
            {
                return CreatePublicKeyToCache(isMemoryCache).ToPkcsPublicKey();//生成公钥私钥 时效两小时更换
            }
            return pubkey.ToString();
        }

        /// <summary>
        /// 根据RSA公钥获取RSA私钥，内部使用，请勿把RSA私钥公开出去
        /// </summary>
        /// <param name="publicKey">公钥key</param>
        /// <param name="isMemoryCache">是否使用MemoryCache</param>
        /// <returns></returns>
        public static string GetPrivateKeyFromCache(string publicKey, bool isMemoryCache = false)
        {
            if (!publicKey.IsNotNullAndEmpty()) return "";

            CacheHelper helper = new CacheHelper(isMemoryCache);
            string keys = helper.Get<string>(String.Format(CacheKeys.ServerPublicPriKeyMd5, DEncrypt.EncryptMd532(publicKey)));
            if (keys != null)
            {
                string[] keyarray = keys.Split(":");
                return keyarray[1].ToString();
            }

            return "";
        }
    }
}
